package com.gexiaobao.pigeon.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.model.bean.AboutPassDataResponse
import com.gexiaobao.pigeon.app.model.bean.AboutThisOrgResponse
import com.gexiaobao.pigeon.app.model.bean.AboutThisSeasonResponse
import com.gexiaobao.pigeon.app.model.bean.AppBaseListResponse
import com.gexiaobao.pigeon.app.model.bean.AppMultipleProjectList
import com.gexiaobao.pigeon.app.model.bean.AppPassProjectResponse
import com.gexiaobao.pigeon.app.model.bean.AppPassSignOrderResponse
import com.gexiaobao.pigeon.app.model.bean.AppRaceOrderList
import com.gexiaobao.pigeon.app.model.bean.AppTeamProjectList
import com.gexiaobao.pigeon.app.model.bean.BaseSignListResponse
import com.gexiaobao.pigeon.app.model.bean.DetailAllResponse
import com.gexiaobao.pigeon.app.model.bean.LivePerformanceResponse
import com.gexiaobao.pigeon.app.model.bean.NumberOfPigeonResponse
import com.gexiaobao.pigeon.app.model.bean.PassInfoResponse
import com.gexiaobao.pigeon.app.model.bean.PaySignResponse
import com.gexiaobao.pigeon.app.model.bean.RaceDetailInfoResponse
import com.gexiaobao.pigeon.app.model.bean.ShedIncomeAndExpenditureResponse
import com.gexiaobao.pigeon.app.model.bean.SignProjectResponse
import com.gexiaobao.pigeon.app.model.bean.UiState
import com.gexiaobao.pigeon.app.model.bean.VisitMemberListResponse
import com.gexiaobao.pigeon.app.model.param.ReSendSMSParam
import com.gexiaobao.pigeon.app.model.param.SaveGroupParam
import com.gexiaobao.pigeon.app.model.param.SaveInfoSignParam
import com.gexiaobao.pigeon.app.model.param.SignInfoParam
import com.gexiaobao.pigeon.app.network.ListDataUiState
import com.gexiaobao.pigeon.app.network.apiService
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.RequestBody
import java.io.File

/**
 * @Author      : hxw
 * @Date        : 2024/6/27 8:24
 * @Describe    :
 */
class OrgRaceViewModel : BaseViewModel() {

    private var pageNo = 1
    private var pageSize = 20

    /** 获取归巢视频 */
    val passVideoResult: MutableLiveData<UiState> = MutableLiveData()
    fun getPassVideo(passId: Int, pigeonId: Int, ringId: String) {
        request({ apiService.getPassVideo(passId, pigeonId, ringId) }, {
            val result = UiState(isSuccess = true, addr = it.addr, msg = it.msg)
            passVideoResult.value = result
        }, {
            val result = UiState(isSuccess = false, errorMsg = it.msg)
            passVideoResult.value = result
        })
    }

    /** 重新发送验证码  */
    var reSendSMSResult: MutableLiveData<UiState> = MutableLiveData()
    fun reSendSMS(body: ReSendSMSParam) {
        request(
            { apiService.reSendSMS(body) }, {
                val result = UiState(isSuccess = true)
                reSendSMSResult.value = result
            }, {
                val result = UiState(isSuccess = false, errorMsg = it.msg)
                reSendSMSResult.value = result
            }
        )
    }

    /**  立即支付  */
    var payNowResult: MutableLiveData<ResultState<Any>> = MutableLiveData()
    fun payNow(body: RequestBody) {
        request(
            { apiService.payNow(body) },
            payNowResult,
            false,
            appContext.getString(R.string.loading)
        )
    }

    /**  关赛报名申请支付  */
    var paySign: MutableLiveData<PaySignResponse> = MutableLiveData()
    fun paySign(body: RequestBody) {
        request({ apiService.paySign(body) }, {
            paySign.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

    /**  获取团体赛报名列表  */
    var getAppTeamSignListResult: MutableLiveData<Any> = MutableLiveData()
    fun getAppTeamSignList(raceId: String) {
        request({ apiService.getAppTeamSignList(raceId) }, {
            getAppTeamSignListResult.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

    /**  比赛详细信息  */
    var detailInfoResult: MutableLiveData<RaceDetailInfoResponse> = MutableLiveData()
    fun getPassDetailApp(id: String) {
        request({ apiService.getPassDetailApp(id) }, {
            detailInfoResult.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

    /** 比赛结果 */
    var raceResultResult: MutableLiveData<LivePerformanceResponse> = MutableLiveData()
    fun getOrgPassResult(
        isRefresh: Boolean,
        pageSize: Int,
        pageNo: Int,
        passId: String,
        sortType: String,
        memberNum: String,
        ringId: String,
        fosterName: String,
        qStr: String
    ) {
        request({ apiService.orgPassResult(passId, pageSize, pageNo, sortType, memberNum, ringId, fosterName, qStr) }, {
            raceResultResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取app关赛的详情（参赛奖）   */
    val appProjectResult: MutableLiveData<AppPassProjectResponse> = MutableLiveData()
    fun getAppPassProject(projectId: String) {
        request({ apiService.getAppPassProject(projectId, pageNo, 99999) }, {
            appProjectResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取app多关单只赛的详情(鸽王赛)   */
    val appMultipleProjectResult: MutableLiveData<ListDataUiState<AppMultipleProjectList>> = MutableLiveData()
    fun getAppMultipleProject(isRefresh: Boolean, projectId: String) {
        if (isRefresh) {
            pageNo = 1
        }
        request({ apiService.getAppMultipleProject(projectId, pageNo, pageSize) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.list
            )
            appMultipleProjectResult.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                isRefresh = isRefresh,
                errMessage = it.msg,
                listData = arrayListOf<AppMultipleProjectList>()
            )
            appMultipleProjectResult.value = listDataUiState
        })
    }

    /** 根据会员id获取公棚赛鸽列表  */
    val orgMinePigeonResult: MutableLiveData<ListDataUiState<NumberOfPigeonResponse.ListBean>> = MutableLiveData()
    fun getLoftPigeonListByMemberId(isRefresh: Boolean, id: Int) {
        if (isRefresh) {
            pageNo = 1
        }
        request({ apiService.getLoftPigeonListByMemberId(pageNo, pageSize, id) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.list
            )
            orgMinePigeonResult.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                isRefresh = isRefresh,
                errMessage = it.msg,
                listData = arrayListOf<NumberOfPigeonResponse.ListBean>()
            )
            orgMinePigeonResult.value = listDataUiState
        })
    }

    /** 获取app团体赛的详情  */
    val appTeamResult: MutableLiveData<ListDataUiState<AppTeamProjectList>> = MutableLiveData()
    fun getAppTeamProject(isRefresh: Boolean, projectId: String) {
        if (isRefresh) {
            pageNo = 1
        }
        request({ apiService.getAppTeamProject(projectId, pageNo, pageSize) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.list
            )
            appTeamResult.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                isRefresh = isRefresh,
                errMessage = it.msg,
                listData = arrayListOf<AppTeamProjectList>()
            )
            appTeamResult.value = listDataUiState
        })
    }

    /** 获取app单关单只赛的详情  */
    val signProjectResult: MutableLiveData<SignProjectResponse> = MutableLiveData()
    fun getAppSignProject(projectId: String) {
        request({ apiService.getAppSignProject(projectId, pageNo, 999999) }, {
            signProjectResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取1的比赛数据  */
    val memberAllMoneyResult: MutableLiveData<ShedIncomeAndExpenditureResponse> = MutableLiveData()
    fun getRaceMemberAllMoney(memberId: Int) {
        request({ apiService.getRaceMemberAllMoney(memberId) }, {
            memberAllMoneyResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取鸽主本赛季数据  */
    val aboutSeasonResult: MutableLiveData<AboutThisSeasonResponse> = MutableLiveData()
    fun getUserSeasonData(passId: Int) {
        request({ apiService.getUserSeasonData(passId) }, {
            aboutSeasonResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取鸽主本公棚数据  */
    val aboutLoftResult: MutableLiveData<AboutThisOrgResponse> = MutableLiveData()
    fun getMemberLoftData(raceId: Int, memberId: Int) {
        request({ apiService.getMemberLoftData(raceId, memberId) }, {
            aboutLoftResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取鸽主本关卡数据  */
    val aboutPassResult: MutableLiveData<AboutPassDataResponse> = MutableLiveData()
    fun getMemberLoftPassData(passId: Int, memberId: Int) {
        request({ apiService.getMemberLoftPassData(passId, memberId) }, {
            aboutPassResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取app关卡的项目列表  */
    val appPassProjectResult: MutableLiveData<Any> = MutableLiveData()//ArrayList<ListOfAwardsResponse>
    fun getAppPassProjectList(passId: String) {
        request({ apiService.getAppPassProjectList(passId) }, {
            appPassProjectResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 上传缴费凭证(关塞报名)  */
    val uploadPayResult: MutableLiveData<Any> = MutableLiveData()
    fun uploadPayFile(orderId: Int, proofFile: File) {
        val fileList = HashMap<String, File?>()
        val hashMap = HashMap<String, String>()
        hashMap["orderId"] = orderId.toString()
        fileList["payFile"] = proofFile
        val body = SettingUtil.filesToMultipartBody(fileList, hashMap)
        request({ apiService.uploadPayFile(body) }, {
            uploadPayResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取单用户下探视棚号列表  */
    val visitMemberResult: MutableLiveData<VisitMemberListResponse> = MutableLiveData()
    fun getVisitMemberNoList(raceId: String) {
        request({ apiService.getVisitMemberNoList(raceId) }, {
            visitMemberResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 可报名的赛鸽列表  */
    var memberTeamResult: MutableLiveData<Any> = MutableLiveData()//MemberTeamResponse
    fun getAppMemberTeam(raceId: String, memberId: Int) {
        request({ apiService.getAppMemberTeam(raceId, memberId) }, {
            memberTeamResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 保存app团体赛  */
    var saveTeamResult: MutableLiveData<Any> = MutableLiveData()
    fun saveAppTeam(body: SaveGroupParam) {
        request({ apiService.saveAppTeam(body) }, {
            saveTeamResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取项目列表  */
    var appBaseResult: MutableLiveData<AppBaseListResponse> = MutableLiveData()
    fun getAppBaseList(raceId: Int, memberId: Int) {
        request({ apiService.getAppBaseList(raceId.toString(), memberId) }, {
            appBaseResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** app保存报名  */
    var signInfoResult: MutableLiveData<Any> = MutableLiveData()
    fun saveAppSignInfo(param: SignInfoParam) {
        request({ apiService.saveAppSignInfo(param) }, {
            signInfoResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取报名表格列表  */
    var signListResult: MutableLiveData<BaseSignListResponse> = MutableLiveData()
    fun getAppBaseSignList(baseId: String, memberId: Int, orderId: Int) {
        request({ apiService.getAppBaseSignList(baseId, memberId, orderId) }, {
            signListResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** app保存报名  */
    var saveSignInfoResult: MutableLiveData<Any> = MutableLiveData()
    fun saveAppSignInfo(body: SaveInfoSignParam) {
        request({ apiService.saveAppSignInfo(body) }, {
            saveSignInfoResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取app订单详情  */
    var getAppOrderResult: MutableLiveData<AppPassSignOrderResponse> = MutableLiveData()
    fun getAppOrder(orderId: String) {
        request({ apiService.getAppOrder(orderId) }, {
            getAppOrderResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取关卡信息（包含关卡成绩） */
    val passInfoResult: MutableLiveData<PassInfoResponse> = MutableLiveData()
    fun getAppPassInfo(passId: Int) {
        request({ apiService.getAppPassInfo(pageNo, 999999, passId) }, {
            passInfoResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获取综合数据 */
    val detailAllResult: MutableLiveData<DetailAllResponse> = MutableLiveData()
    fun getDataAll(memberId: Int, passId: Int) {
        request({ apiService.getDataAll(memberId, passId) }, {
            detailAllResult.value = it
        }, {
            RxToast.warning(it.msg)
        })
    }

    /** 获获取比赛的app订单列表 */
    val appRaceOrderResult: MutableLiveData<ListDataUiState<AppRaceOrderList>> = MutableLiveData()
    fun getAppRaceOrderList(isRefresh: Boolean, raceId: String, orderStatus: Int) {
        if (isRefresh) {
            pageNo = 1
        }
        request({ apiService.getAppRaceOrderList(raceId, pageNo, pageSize, orderStatus) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.list
            )
            appRaceOrderResult.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                isRefresh = isRefresh,
                errMessage = it.msg,
                listData = arrayListOf<AppRaceOrderList>()
            )
            appRaceOrderResult.value = listDataUiState
        })
    }

    /** 获取成绩直播页面所有需要的数据 */
    fun getLiveStreamingData(
        pageSize: Int,
        pageNo: Int,
        passId: String,
        raceId: String,
        sortType: String,
        memberNum: String,
        ringId: String,
        fosterName: String,
        qStr: String
    ) {
        viewModelScope.launch {
            try {
                val result1 = apiService.getPassDetailApp(passId)
                detailInfoResult.value = result1.data

                val result2 = apiService.orgPassResult(passId, pageSize, pageNo, sortType, memberNum, ringId, fosterName, qStr)
                raceResultResult.value = result2.data

                val result3 = apiService.getVisitMemberNoList(raceId)
                visitMemberResult.value = result3.data

            } catch (e: Exception) {
                LogUtils.warnInfo("MainViewModel", "Error occurred: ${e.localizedMessage}")
            }
        }

    }

}